package com.duobaoyu.dby.supply.biz.util;

import cn.hutool.core.map.MapUtil;
import com.alibaba.ttl.TransmittableThreadLocal;
import com.duobaoyu.dby.supply.biz.constant.SupplyChainConstants;
import com.google.common.collect.Maps;
import org.springframework.util.CollectionUtils;

import java.util.Map;

/**
 * @author yanhan
 * @version 1.0.0
 * @Description ThreadLocal 工具类
 * @createTime 2022/08/17 14:30:00
 */
public class ThreadLocalUtils {

	/**
	 * 请求头业务参数
	 */
	private static final ThreadLocal<Map<String, Object>> HEADS_BIZ_PARAM_THREAD_LOCAL = new TransmittableThreadLocal<>();

	public static Map<String, Object> getHeadsBizParamThreadLocal() {
		return HEADS_BIZ_PARAM_THREAD_LOCAL.get();
	}

	public static void setHeadsBizParamThreadLocal(Map<String, Object> params) {
		HEADS_BIZ_PARAM_THREAD_LOCAL.set(params);
	}

	public static void remove() {
		HEADS_BIZ_PARAM_THREAD_LOCAL.remove();
	}

	public static void put(String key, Object value) {
		Map<String, Object> paramMap = getHeadsBizParamThreadLocal();
		if (MapUtil.isEmpty(paramMap)) {
			paramMap = Maps.newHashMap();
			setHeadsBizParamThreadLocal(paramMap);
		}
		paramMap.put(key, value);
	}

	public static <T> T get(String key, Class<T> clazz) {
		Map<String, Object> paramMap = getHeadsBizParamThreadLocal();
		if (MapUtil.isEmpty(paramMap) || !paramMap.containsKey(key)) {
			return null;
		}
		return ((T) paramMap.get(key));
	}

	/**
	 * 获取业务编码
	 *
	 * @return
	 */
	public static String getBizCode() {
		Map<String, Object> heads = HEADS_BIZ_PARAM_THREAD_LOCAL.get();
		if (!CollectionUtils.isEmpty(heads) && heads.containsKey(SupplyChainConstants.BIZ_CODE)) {
			return ((String) heads.get(SupplyChainConstants.BIZ_CODE));
		}
		return null;
	}
}
